package edu.zjucst.spb.controller.user;

import cn.hutool.core.util.IdUtil;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.wf.captcha.SpecCaptcha;
import edu.zjucst.spb.domain.ResponseResult;
import edu.zjucst.spb.domain.vo.user.CaptchaVO;
import edu.zjucst.spb.enums.UserBusinessStatusEnum;
import edu.zjucst.spb.exception.BizException;
import edu.zjucst.spb.pkg.redis.UserRedisDao;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@Validated
@Api(value = "图片验证码相关接口", tags = {"图片验证码相关接口"})
@ApiSupport(author = "qingo")
@RequestMapping("/captcha")
public class CaptchaController {
    public static final TimeUnit timeUnit = TimeUnit.MINUTES;
    public long expiration = 5;
    @Autowired
    private UserRedisDao userRedisDao;

    @ApiOperation("获取图片验证码")
    @GetMapping
    public ResponseResult<CaptchaVO> captcha(HttpServletRequest request, HttpServletResponse response) {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48);
        String verCode = specCaptcha.text();
        // 存入redis并设置过期时间, 将key和base64返回给前端
        CaptchaVO captchaVO = new CaptchaVO();
        System.out.println(verCode);
        captchaVO.setKey(userRedisDao.setCaptchaKey(IdUtil.randomUUID(), verCode.toLowerCase(), expiration, timeUnit));
        captchaVO.setImage(specCaptcha.toBase64());
        return ResponseResult.success(captchaVO);
    }

    @ApiOperation("校验图片验证码")
    @GetMapping("/verify")
    public ResponseResult<Object> verifyCaptcha(@RequestParam @NotBlank String verKey, @RequestParam @NotBlank String verCode) {
        // 获取redis中的验证码
        String redisCode = userRedisDao.get(verKey);
        System.out.println(verKey + " " + verCode + " " + redisCode);
        if (!verCode.trim().toLowerCase().equals(redisCode)) {
            throw new BizException(UserBusinessStatusEnum.VERIFICATION_EXPIRED.getCode(), UserBusinessStatusEnum.VERIFICATION_EXPIRED.getDescription());
        }
        userRedisDao.remove(verKey);
        return ResponseResult.success();
    }
}
